<?php

namespace app\controllers;

use Yii;
use yii\web\Response;
use app\components\BaseWechatController;
use app\components\Api;
use app\components\Wechat;
use app\components\Loyalty;
use app\components\Log;
use app\models\JsTicket;
use yii\helpers\ArrayHelper;

class WechatMemberCardController extends BaseWechatController
{
    const CARD1 = 'p2Rmrt4MWpgcjO5rh1q7v8elLt8w';
    
    const CARD_MOMO = 'pPPpJuA5Yd-xy0Wz6BMaZ3yAABl4';

    const OPENID_MOMO = 'oPPpJuCh3xXk5EvrUGz7qo9l60xw';

    const OLD_BACKIMG = 'https://mmbiz.qpic.cn/mmbiz_jpg/UzsLSJicrzHdQb3012ncQrAAxLlTEHUUib3xP8mSDgxxnFbCrZyGhJp2BpIG2yJFUaBbh3tqCubjJ2Wz2EgkqSJQ/0';
    
    const WEBFORM = 'https://webform.xgate.com/app/index.php/webforms/form/form?encid=e6f6e18c-70ec-7c51-8403-c607d27d59c6&tracker=350e92b9-5986-4f05-f72c-77289fac5343';

    // 会员卡首页
    public function actionIndex()
    {
        // $re = Wechat::userinfo([self::OPENID_MOMO]);
        // $re = Loyalty::customer_search(['mobile' => '1']);
        // $this->bp($re);
        return $this->render('index');
    }

    // 创建会员卡
    public function actionCreate()
    {
        $data = $this->create();
        $re = null;

        if (Yii::$app->request->isPost) {
            $re = Wechat::card_create($data);
        }

        return $this->render('create', [
            'data' => $data,
            're' => $re,
        ]);
    }

    // 更新会员卡
    public function actionUpdate()
    {
        $data = $this->update();
        $re = null;

        if (Yii::$app->request->isPost) {
            $re = Wechat::card_update($data);
        }

        return $this->render('update', [
            'data' => $data,
            're' => $re,
        ]);
    }

    // 开卡字段
    public function actionFields()
    {
        $data = [
            'card_id' => self::CARD_MOMO,
            'required_form' => [
                'can_modify' => false, // 当前结构内的字段是否允许用户激活后再次修改，商户设置为true时，需要接收相应事件通知处理修改事件
                'common_field_id_list' => [
                    'USER_FORM_INFO_FLAG_NAME',
                    'USER_FORM_INFO_FLAG_MOBILE',
                    'USER_FORM_INFO_FLAG_SEX',
                ],
            ],
            // 'optional_form' => [
            //     'can_modify' => false,
            //     'common_field_id_list' => [
            //         'USER_FORM_INFO_FLAG_BIRTHDAY',
            //         'USER_FORM_INFO_FLAG_EMAIL',
            //     ],
            // ]
        ];
        $re = null;

        if (Yii::$app->request->isPost) {
            $re = Wechat::card_activate_form($data);
        }

        return $this->render('fields', [
            'data' => $data,
            're' => $re,
        ]);
    }

    // 获取会员卡字段
    public function actionView()
    {
        $data = [
            'card_id' => 'p2Rmrt4JId6z4hETx3HTVnLZ68K4',
        ];

        $re = Wechat::card_get($data);

        return $this->render('view', [
            're' => $re,
        ]);
    }

    // 绑定支付即会员规则
    // rule_id 444621532
    public function actionBind()
    {
        $re = null;

        $rule = [
            'rule_id' => '444621532',
        ];

        $re = Wechat::paygiftcard_get($rule);

        $data = [
            'rule_info' => [
                'type' => 'RULE_TYPE_PAY_MEMBER_CARD', // 默认
                'base_info' => [
                    'mchid_list' => [ // 商户号列表，是一个数组结构 必填
                        '1368056102',
                    ],
                    'begin_time' => time(), // 规则开始时间 必填
                    'end_time' => time() + 864000000, // 规则结束时间 必填
                ],
                'member_rule' => [
                    'card_id' => 'p2Rmrt4JId6z4hETx3HTVnLZ68K4', // 要赠送的会员卡card_id 必填
                    'least_cost' => '1', // 单次消费送会员卡的金额下限，以分为单位 必填
                    'max_cost' => '1000000', // 单次消费送会员卡的金额上限，以分为单位 必填
                    // 'jump_url' => '', // 商户自定义领卡网页链接，填入后点击支付即会员消息会跳转至商户网页领卡
                ],
            ],
        ];

        if (Yii::$app->request->isPost) {
            $re = Wechat::paygiftcard_create($data);
        }

        return $this->render('bind', [
            'data' => $data,
            're' => $re,
        ]);
    }

    // 激活会员卡页面
    // 采用activate_url 模式
    // http://winshare.onthemooner.com/index.php/wechat-member-card/activate
    // ?card_id=p2Rmrt4JId6z4hETx3HTVnLZ68K4
    // &encrypt_code=EsayGjRyefrbkweKMFcitFfa%2FvInLqlJUfqnR6JfkXc%3D
    // &openid=o2Rmrtzjjg68MAirKb8XUJ7YdWc0
    // public function actionActivate()
    // {
    //     if (isset($_GET['card_id'])) {
    //         $card_id = $_GET['card_id'];
    //     }
    //     if (isset($_GET['encrypt_code'])) {
    //         $encrypt_code = $_GET['encrypt_code'];
    //     }
    //     if (isset($_GET['openid'])) {
    //         $openid = $_GET['openid'];
    //     }
    //     $re = Wechat::code_decrypt(['encrypt_code' => $encrypt_code]);
    //     if ($re['errmsg'] == 'ok') {
    //         $code = $re['code'];
    //     }

    //     $data = [
    //         'membership_number' => 'MOMO' . mt_rand(0, 10000),
    //         'code' => $code,
    //         'card_id' => $card_id,
    //     ];

    //     $re = Wechat::card_activate($data);

    //     return $this->render('activate', [
    //         're' => $re,
    //     ]);
    // }

    // MOMO测试激活
    public function actionActivate()
    {
        Log::debug('Activate Start');
        
        if (isset($_GET['is_webform']) && $_GET['is_webform'] == 1) {
            // 构造激活数据
            $data = [
                'membership_number' => 'MOMO'. mt_rand(0, 9999),
                'code' => $_GET['code'],
                'card_id' => self::CARD_MOMO,
            ];Log::debug('new_member_activate', $data);
            // 激活
            $re = Wechat::card_activate($data);
        } else {
            // 获取GET
            if (isset($_GET['card_id'])) {
                $card_id = $_GET['card_id'];
            }
            if (isset($_GET['encrypt_code'])) {
                $encrypt_code = $_GET['encrypt_code'];
            }
            if (isset($_GET['openid'])) {
                $openid = $_GET['openid'];
            }
            if (isset($_GET['activate_ticket'])) {
                $activate_ticket = $_GET['activate_ticket'];
            }
            // 解密code，获取真实code
            $re = Wechat::code_decrypt(['encrypt_code' => $encrypt_code]);
            if ($re['errmsg'] == 'ok') {
                $code = $re['code'];
            }

            // 获取用户填写的信息
            $data = [
                'activate_ticket' => $activate_ticket,
            ];
            $re = Wechat::card_temp_userinfo_get($data);Log::debug('card_temp_userinfo_get', $re);

            if ($re['errmsg'] == 'ok') {
                $info = $re['info'];
                foreach($info['common_field_list'] as $v) {
                    if ($v['name'] == 'USER_FORM_INFO_FLAG_MOBILE') {
                        $mobile = empty($v['value']) ? '' : $v['value'];
                    } elseif ($v['name'] == 'USER_FORM_INFO_FLAG_NAME') {
                        $last_name = empty($v['value']) ? '' : $v['value'];
                    } elseif ($v['name'] == 'USER_FORM_INFO_FLAG_SEX') {
                        $gender = empty($v['value']) ? '' : $v['value'];
                    }
                }
            }
            // 非必填字段有问题
            $webform_url = self::WEBFORM . '&mobile=' . $mobile . '&last_name=' . $last_name . '&code=' . $code . '&gender=' . $gender .
            '&is_webform=1';Log::debug('webform_url', $webform_url);
            return $this->redirect($webform_url);
        }
        Log::debug('Activate End');
        return $this->render('activate', [
            're' => $re,
        ]);
    }

    // 激活会员卡页面
    // 采用wx_activate 模式
    // http://winshare.onthemooner.com/index.php/wechat-member-card/activate
    // ?card_id=p2Rmrt4JId6z4hETx3HTVnLZ68K4
    // &encrypt_code=EsayGjRyefrbkweKMFcitMtIxVToY7drWuyttuO8Cuk%3D
    // &openid=o2Rmrt6MhYjT9x3zEezTUAbD-c3E
    // &outer_str=4200000004201710178627950199
    // &activate_ticket=fDZv9eMQAFfrNr3XBoqhb8%2Bqluz6BxKyPs2shE6f3KW6kDtTURaLAfYTFQpcM6cYcboiqxRCIGohuVHtEli%2BoHjMSubRYseOFxTeJVtJyB4%3D
    // public function actionActivate()
    // {
    //     Log::debug('Activate Start');
    //     // http://winshare.onthemooner.com/index.php/wechat-member-card/activate?last_name=%E5%AD%99%E6%96%87%E9%9C%8F&mobile=17713607873&gender=%E7%94%B7&email=437573323%40qq.com&birth_yyyy=1991&birth_mm=4&birth_dd=6&code=865584423614
    //     if (isset($_GET['is_webform']) && $_GET['is_webform'] == 1) {
    //         $re = Loyalty::customer_get(['code' => $_GET['code']]);Log::debug('customer_get', $re);
    //         // 构造激活数据
    //         $data = [
    //             'membership_number' => $re['card_number'],
    //             'code' => $_GET['code'],
    //             'card_id' => self::CARD_MOMO,
    //             'background_pic_url' => '',
    //         ];Log::debug('new_member_activate', $re);
    //         // 激活
    //         $re = Wechat::card_activate($data);
    //     } else {
    //         // 获取GET
    //         if (isset($_GET['card_id'])) {
    //             $card_id = $_GET['card_id'];
    //         }
    //         if (isset($_GET['encrypt_code'])) {
    //             $encrypt_code = $_GET['encrypt_code'];
    //         }
    //         if (isset($_GET['openid'])) {
    //             $openid = $_GET['openid'];
    //         }
    //         if (isset($_GET['activate_ticket'])) {
    //             $activate_ticket = $_GET['activate_ticket'];
    //         }
    //         // 解密code，获取真实code
    //         $re = Wechat::code_decrypt(['encrypt_code' => $encrypt_code]);
    //         if ($re['errmsg'] == 'ok') {
    //             $code = $re['code'];
    //         }

    //         // 获取用户填写的信息
    //         $data = [
    //             'activate_ticket' => $activate_ticket,
    //         ];
    //         $re = Wechat::card_temp_userinfo_get($data);Log::debug('card_temp_userinfo_get', $re);

    //         if ($re['errmsg'] == 'ok') {
    //             $info = $re['info'];
    //             foreach($info['common_field_list'] as $v) {
    //                 if ($v['name'] == 'USER_FORM_INFO_FLAG_MOBILE') {
    //                     $mobile = empty($v['value']) ? '' : $v['value'];
    //                 } elseif ($v['name'] == 'USER_FORM_INFO_FLAG_NAME') {
    //                     $last_name = empty($v['value']) ? '' : $v['value'];
    //                 } elseif ($v['name'] == 'USER_FORM_INFO_FLAG_SEX') {
    //                     $gender = empty($v['value']) ? '' : $v['value'];
    //                 } elseif ($v['name'] == 'USER_FORM_INFO_FLAG_BIRTHDAY') {
    //                     $birthday = empty($v['value']) ? '' : $v['value'];
    //                     if (!empty($birthday)) {
    //                         $birthday_arr = explode('-', $birthday);
    //                         $birth_yyyy = $birthday_arr[0];
    //                         $birth_mm = $birthday_arr[1];
    //                         $birth_dd = $birthday_arr[2];
    //                     }
    //                 } elseif ($v['name'] == 'USER_FORM_INFO_FLAG_EMAIL') {
    //                     $email = empty($v['value']) ? '' : $v['value'];
    //                 }
    //             }
    //         }
    //         // $birthday = '1991-4-6';
    //         // $openid = 'o2Rmrtzjjg68MAirKb8XUJ7YdWc0';
    //         // $last_name = '孙文霏';
    //         // $mobile = '17713607873';
    //         // $code = '865584423614';
    //         // $card_id = 'p2Rmrt4JId6z4hETx3HTVnLZ68K4';
    //         // $gender = '男';
    //         // $email = '437573323@qq.com';
    //         // 先查询Loyalty API是否已经有这个用户，有则直接激活
    //         $re = Loyalty::customer_search(['mobile' => $mobile]);Log::debug('customer_search', $re);
    //         if ($re['status'] == 'success') {
    //             foreach($re['result']['customers'] as $v) {
    //                 $loyaltyInfo = $v;
    //             }
    //             // 更新数据
    //             $data = [
    //                 'code' => $loyaltyInfo['code'],
    //                 'last_name' => $last_name,
    //                 'gender' => $gender,
    //                 'email' => $email,
    //                 'birth_yyyy' => $birth_yyyy,
    //                 'birth_mm' => $birth_mm,
    //                 'birth_dd' => $birth_dd,
    //                 'wechat_openid' => $openid,
    //             ];
    //             $re = Loyalty::customer_update($data);Log::debug('customer_update', $re);
    //             // 构造激活数据
    //             $data = [
    //                 'membership_number' => $loyaltyInfo['card_number'],
    //                 'code' => $code,
    //                 'card_id' => self::CARD_MOMO,
    //                 // 'background_pic_url' => self::OLD_BACKIMG,
    //             ];Log::debug('old_member_activate', $re);
    //             // 激活
    //             $re = Wechat::card_activate($data);
    //         } else {
    //             // 非必填字段有问题
    //             $webform_url = self::WEBFORM . '&mobile=' . $mobile . '&last_name=' . $last_name . '&code=' . $code . '&gender=' . $gender . '&email=' . $email .
    //             '&birth_yyyy=' . $birth_yyyy . '&birth_mm=' . $birth_mm . '&birth_dd=' . $birth_dd . '&is_webform=1';Log::debug('webform_url', $webform_url);
    //             return $this->redirect($webform_url);
    //         }
    //     }
    //     Log::debug('Activate End');
    //     return $this->render('activate', [
    //         're' => $re,
    //     ]);
    // }

    // 会员卡的base_info字段
    public function baseInfo()
    {
        $baseInfo = [
            'logo_url' => 'https://mmbiz.qpic.cn/mmbiz_jpg/UzsLSJicrzHcIKMd81Tm61Z4NujiaLQXSIVPQeDxlAaqop3G9XvQJymAicZFQx5nNmjnWLibq74DBo6UmXma3FISKg/0', // 卡券的商户logo，建议像素为300*300 必填
            'code_type' => 'CODE_TYPE_TEXT', // Code展示类型 必填
            'brand_name' => 'Jebsen', // 商户名字,字数上限为12个汉字 必填
            'title' => 'Jebsen测试卡', // 卡券名，字数上限为9个汉字 必填
            'color' => 'Color030', // 券颜色。按色彩规范标注填写Color010-Color100 必填
            'notice' => '使用时向服务员出示此券', // 卡券使用提醒，字数上限为16个汉字 必填
            'description' => '仅用于测试', // 卡券使用说明，字数上限为1024个汉字 必填
            'sku' => [
                'quantity' => '1000', // 卡券库存的数量 必填
            ],
            'date_info' => [
                'type' => 'DATE_TYPE_PERMANENT', // 永久有效类型 必填
            ],
            // 'location_id_list' => [], // 门店位置ID。调用POI门店管理接口获取门店位置ID 选填
            'use_all_locations' => true, // 会员卡是否支持全部门店，填写后商户门店更新时会自动同步至卡券 选填
            'get_limit' => 1, // 每人可领券的数量限制，建议会员卡每人限领一张 选填
            // 'pay_info' => [ // 选填
            //     'swipe_card' => [ // 选填
            //         // 'is_swipe_card' => true, // 是否设置该会员卡支持拉出微信支付刷卡界面 选填
            //         'is_pay_and_qrcode' => true, // 是否设置该会员卡中部的按钮同时支持微信支付刷卡和会员卡二维码 选填
            //     ],
            // ],
        ];
        return $baseInfo;
    }

    // 会员卡的advanced_info字段
    public function advancedInfo()
    {
        $advancedInfo = [];
        return $advancedInfo;
    }

    // 创建会员卡的字段
    // p2Rmrt56_YLiCcUp3QDOs4lIQyo8 快速买单卡号
    public function create()
    {
        // 创建会员卡的基本数据
        $baseInfo = $this->baseInfo();
        $advancedInfo = $this->advancedInfo();

        $wx_activate_after_submite_url = 'http://winshare.onthemooner.com/index.php/wechat-member-card/activate';

        $data = [
            'card' => [
                'card_type' => 'MEMBER_CARD',
                'member_card' => [
                    'base_info' => $baseInfo,
                    'advanced_info' => $advancedInfo,
                    'prerogative' => '测试', // 会员卡特权说明,限制1024汉字 必填
                    'supply_bonus' => true, // 显示积分，填写true或false，如填写true，积分相关字段均为必填,若设置为true则后续不可以被关闭
                    'supply_balance' => false, // 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用
                    // 'wx_activate' => true, // 激活会员卡的url
                    // 'wx_activate_after_submit' => true, // 是否设置跳转型一键激活
                    // 'wx_activate_after_submit_url' => $wx_activate_after_submite_url, // 用户提交信息后跳转的网页
                    // 'active_url' => 'http://winshare.onthemooner.com/index.php/wechat-member-card/h5active',
                    'auto_activate' => true,
                    'bonus_rule' => [ // 选填
                        'cost_money_unit' => 1, // 消费金额,以分为单位
                        'increase_bonus' => 1, // 对应增加的积分
                        'max_increase_bonus' => 10, // 用户单次可获取的积分上限
                        'init_increase_bonus' => 100, // 初始设置积分
                        'cost_bonus_unit' => 10, // 每使用5积分
                        'reduce_money' => 1, // 抵扣xx元，（这里以分为单位）
                        'least_money_to_use_bonus' => 10, // 抵扣条件，满xx元（这里以分为单位）可用
                        'max_reduce_bonus' => 100, // 抵扣条件，单笔最多使用xx积分
                    ],
                ],
            ],
        ];

        return $data;
    }

    public function update()
    {
        // 创建会员卡的基本数据
        $baseInfo = [];
        $advancedInfo = $this->advancedInfo();

        $wx_activate_after_submite_url = 'http://winshare.onthemooner.com/index.php/wechat-member-card/activate';

        $data = [
            'card_id' => 'p2Rmrt4JId6z4hETx3HTVnLZ68K4',
            'member_card' => [
                'base_info' => $baseInfo,
                'advanced_info' => $advancedInfo,
                'prerogative' => '会员卡特权说明', // 会员卡特权说明,限制1024汉字 必填
                'supply_bonus' => true, // 显示积分，填写true或false，如填写true，积分相关字段均为必填,若设置为true则后续不可以被关闭
                'supply_balance' => false, // 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用
                'wx_activate' => true, // 激活会员卡的url
                'wx_activate_after_submit' => true, // 是否设置跳转型一键激活
                'wx_activate_after_submit_url' => $wx_activate_after_submite_url, // 用户提交信息后跳转的网页
            ],
        ];

        return $data;
    }

    //客服消息发送会员卡
    public function actionSendCard()
    {
        $openid = 'oPPpJuNSrDwoKcxbqhXW_p_E3E-4';
        $data = [
            // 'touser' => self::OPENID_MOMO,
            'touser' => $openid,
            'msgtype' => 'wxcard',
            'wxcard' => [
                'card_id' => self::CARD_MOMO,
            ],
        ];
        $re = Wechat::card_send($data);
        $this->bp($re);
    }


    //会员积分查询
    public function actionLevel()
    {
        // $card_id = 'p2Rmrt4JId6z4hETx3HTVnLZ68K4';
        // $encrypt_code = 'EsayGjRyefrbkweKMFcitMtIxVToY7drWuyttuO8Cuk%3D';
        if (isset($_GET['card_id'])) {
            $card_id = $_GET['card_id'];
        }
        if (isset($_GET['encrypt_code'])) {
            $encrypt_code = $_GET['encrypt_code'];
        }
        if (empty($card_id) || empty($encrypt_code)) {
            exit('无效的请求');
        }

        // 解密code，获取真实code
        $re = Wechat::code_decrypt(['encrypt_code' => $encrypt_code]);
        // $this->bp($re);
        if ($re['errmsg'] == 'ok') {
            $code = $re['code'];
        } else {
            exit('无效的code');
        }
        $data = [
            "card_id" => $card_id,
            "code" => $code
        ];
        $re = Wechat::card_userinfo_get($data);
        $this->bp($re);
    }


    public function actionUpdateUser()
    {
        // $card_id = 'p2Rmrt4JId6z4hETx3HTVnLZ68K4';
// 解密code，获取真实code
         $encrypt_code = 'EsayGjRyefrbkweKMFcitMtIxVToY7drWuyttuO8Cuk%3D';
        $re = Wechat::code_decrypt(['encrypt_code' => $encrypt_code]);
        $data = [
                "code" => '865584423614',
             "card_id" => "p2Rmrt4MWpgcjO5rh1q7v8elLt8w",
            "background_pic_url" => "https://mmbiz.qlogo.cn/mmbiz/0?wx_fmt=jpeg",
            "record_bonus" => "消费30元，获得3积分",
          //  "bonus" => 20,
             "add_bonus" => 30,
            "balance" => 20,
            "add_balance" => -1,
            "record_balance" => "购买焦糖玛琪朵一杯，扣除金额30元。",
             "custom_field_value1" =>  "8折",
              "custom_field_value2" => "白金",
            "notify_optional" => [
                    "is_notify_bonus" => false,
                "is_notify_balance" => false,
                "is_notify_custom_field1" => false
            ]
        ];
        $r = Wechat::update_user($data);
        echo "<pre/>";
        var_dump($r);die;
    }


    //设置跟随推荐
    public function actionFollow()
    {
//        $data = [
//              "card_id" => "p2Rmrt4MWpgcjO5rh1q7v8elLt8w",
//              "member_card" => [
//                "activate_msg_operation" => [
//                  //若指定的是积分、余额等变动消息赠券，则为modify_msg_operation"url_cell": {
//                    "card_id_list" => [
//                      "p2Rmrt4JId6z4hETx3HTVnLZ68K4"
//                    ],
//                    //"end_time" => 1546275661,
//                    "text" => "恭喜你获得一张50元代金券",
//                   // "url" => "www.qq.com"
//                  ]
//                ]
//              ];
        $data = [
                        "card_id" => "p2Rmrt4MWpgcjO5rh1q7v8elLt8w",
                    "member_card" => [
                            "activate_msg_operation" => [   //若指定的是积分、余额等变动消息赠券，则为modify_msg_operation
                                "url_cell" => [
                                    "card_id_list" => [
                                        "p2Rmrt4JId6z4hETx3HTVnLZ68K4"
                                    ],
                                "end_time" => 1577811661,
                                "text" => "恭喜你10连跪",
//                                "url" => "www.qq.com"
                            ]
                        ]
                    ]
                ];
        $re = Wechat::card_update($data);
        echo "<pre/>";
        var_dump($re);
    }

    public function actionUserList()
    {
        $re = Wechat::user_list();
        echo "<pre/>";
        var_dump($re);
    }

    public function actionUser()
    {
        $re = Wechat::userinfo();
        echo "<pre/>";
        var_dump($re);
    }

    public function actionAddPoints()
    {
        $data = [
            'code' => '123307716173',
            'card_id' => 'p2Rmrt56_YLiCcUp3QDOs4lIQyo8',
            'add_bonus' => '-10',
            'record_bonus' => 'API扣减10积分',
        ];

        $re = Wechat::update_user($data);
        $this->bp($re);        
    }
    
    // ================================ JSSDK SIGN ================================
    public function getSignPackage() 
    {
        $jsapiTicket = $this->getJsTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        Log::debug('string', $string);

        $signature = sha1($string);
        Log::debug('signature', $signature);
        $appId = "wxeca2e361be1de14c";

        $signPackage = array(
            "appId"     => $appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage; 
    }

    //获取js ticket
    public function getJsTicket()
    {
        $time = JsTicket::find()->select('expiration_time,ticket')->orderBy('id DESC')->limit(1)->asArray()->one();
        if($time['expiration_time'] > time()){
            return $time['ticket'];
        }else{
            $ticket = Wechat::get_js_ticket();
            // $this->bp($ticket);exit;
            if($ticket['errmsg'] == "ok"){
                $model = new JsTicket();
                $model->expiration_time = time()+7200;
                $model->ticket = $ticket['ticket'];
                $model->save();
                return $ticket['ticket'];
            }else{
                return false;
            }
        }  
    }

    private function createNonceStr($length = 16) 
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    // ================================ JSSDK SIGN ================================

    public function actionTest()
    {
        // $appId = "wxeca2e361be1de14c";
        // $timestamp = time();
        // //16位随机字符
        // $nonceStr = substr(md5(time() . mt_rand(0,1000)),0,16);
        // //js票据
        // $jsapiTicket = $this->GetJsTicket();
        // //当前url
        // $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";  
        // $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        // // echo $url;exit;
        // //$url = Yii::$app->request->hostInfo.Yii::$app->request->getUrl();
        // $string1 = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        // $signature = sha1($string1);
        $signPackage = $this->getSignPackage();
        return $this->render('test', [
            'signPackage' => $signPackage
        ]);
    }

}
